package fr.jhaccoun.demenager_eco.web.propertyeditor;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import fr.jhaccoun.demenager_eco.produit.EtatUsure;
import fr.jhaccoun.demenager_eco.produit.EtatUsureService;

@Component
public class EtatUsurePropertyEditor extends PropertyEditorSupport {


	@Autowired 
	private EtatUsureService etatUsureService;
	
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		
		if(StringUtils.isBlank(text)){
			setValue(null);
		}else{
			EtatUsure etatUsure = etatUsureService.findByCode(text);
			if(etatUsure == null){
				throw new IllegalArgumentException("l'etat d'usure de code : "+text+" ne doit pas être null");
			}
			setValue(etatUsure);
		}
	}
	
	@Override
	public String getAsText() {
		EtatUsure etatUsure = (EtatUsure) getValue();
		
		if(etatUsure!=null){
			return etatUsure.getCode(); 
		}
		return null;
	}
}
